module.exports = class extends require('egg').Service {
  /** 登录/注册 */
  async sign({ tel, parent_uid, ip }) {
    const { ctx } = this;

    let user = await this.getUserByTel(tel);
    if (!user) {
      // 未注册
      await this.createUser({ tel, parent_uid });
      user = await this.getUserByTel(tel);
    }

    // 更新IP
    await ctx.helper.query({ query: `UPDATE "meet_user" SET "ip" = '${ip}' WHERE tel = '${tel}'` });

    const token = ctx.helper.generateToken({ uid: user.id });
    return token;
  }
  async info(uid) {
    return await this.ctx.helper.query({ query: `SELECT * FROM "meet_user" WHERE id = ${uid}`, find: true });
  }
  async getUserByTel(tel) {
    return await this.ctx.helper.query({ query: `SELECT * FROM "meet_user" WHERE tel = '${tel}'`, find: true });
  }
  /** 新建用户 */
  async createUser({ tel, parent_uid }) {
    const { ctx } = this;
    /** 起始金币 */
    const INIT_COIN = 5;
    const initAvatar =
      'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic4.zhimg.com%2F50%2Fv2-0e98d843ef66ae5e9ec846a7c5f98224_hd.jpg&refer=http%3A%2F%2Fpic4.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1624255432&t=45262a64bd9e0e132889afa6a43ed630';
    await ctx.helper.query({
      query: `INSERT INTO "meet_user" (tel, create_time, total_coin, coin, parent_uid, avatar) VALUES
              ('${tel}', '${ctx.helper.formatTime()}', ${INIT_COIN}, ${INIT_COIN}, ${parent_uid || null}, '${initAvatar}')`
    });

    if (parent_uid) {
      // 拉人奖励
      const INVITE_AWARD = 15;
      await ctx.helper.query({ query: `update "meet_user" set coin = coin + ${INVITE_AWARD} where id = ${parent_uid}` });
    }
  }
};
